package Server_Netty.TCP;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class TCPBytesDataProtocol {
    /**
     * TCP的粘拆包机制
     * 头两个字节的数据表示数据包的长度，后面为真实需要数据
     * DataLen = FirstByte * 256 + SecondByte
     * */
    // Data_Len_Short 是 Lowbyte 和 highbyte 的組合，不是真正的數據長度
    private short Data_Len_Short;
    //消息的内容
    private byte[] content;

    //自定义协议的初始化(构造函数)
    public TCPBytesDataProtocol(short DataLength, byte[] DataContent) {
        this.Data_Len_Short = DataLength;
        this.content = DataContent;
    }

    public short get_Data_Len_Short() {
        return Data_Len_Short;
    }

    public void set_Data_Len_Short(short Data_Len) {
        Data_Len_Short = Data_Len;
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] DataContent) {
        content = DataContent;
    }

    public int get_real_DataLength() {
        short DataLen_LowByte = (short)(Data_Len_Short % 256);
        short DataLen_HighByte = (short)(Data_Len_Short / 256);
        //两个short做运算操作会转成int类型来操作，所以这里的short不需要强转
        int DataLen = DataLen_HighByte * 256 + DataLen_LowByte;
        return DataLen;
    }
}
